package javaer.starter.web.config;

import javaer.starter.constant.StorePathEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * @author yangzhen
 * @date 2022/1/11 17:26
 * @since 1.0.0
 */
@Component
public class FileClearScheduler {
    final int TEN_MINUTE = 10 * 60000;

    private Logger logger = LoggerFactory.getLogger(FileClearScheduler.class);


    @Scheduled(fixedRate = TEN_MINUTE)
    public void archiveClear() {
        doClear();
    }

    private void doClear() {
        try {
            Path path = StorePathEnum.ARCHIVE_PATH.getPath();
            if (!Files.exists(path)) {
                return;
            }

            Files.list(path).forEach(v -> {
                File file = v.toFile();
                if (System.currentTimeMillis() - file.lastModified() > TEN_MINUTE) {
                    file.delete();
                    logger.info("清除文件 {}", v.toString());
                }
            });
        } catch (Exception e) {
            logger.error("执行清除任务异常：", e);
        }
    }
}
